<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="餐厅名称" prop="restaurantName">
        <el-input
          v-model="queryParams.restaurantName"
          placeholder="请输入餐厅名称"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属公司" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="请选择所属公司" clearable size="small"  @change="handleQuery">
          <el-option v-for="item in companys" :key="item.id" :label="item.text" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:restaurant:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:restaurant:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:restaurant:delete']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:restaurant:export']"
        >导出</el-button>
      </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="餐厅名称" align="center" prop="restaurantName" />
      <el-table-column label="餐厅信息" align="center" prop="restaurantInfo" :show-overflow-tooltip="true"/>
      <el-table-column label="联系电话" align="center" prop="telephone" />
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:restaurant:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:restaurant:delete']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属公司" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择所属公司" clearable size="small" style="width: 100%;">
            <el-option v-for="item in companys" :key="item.id" :label="item.text" :value="Number(item.id)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="餐厅名称" prop="restaurantName">
          <el-input v-model="form.restaurantName" maxlength="50" placeholder="请输入餐厅名称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="form.telephone" maxlength="50" placeholder="请输入餐厅联系电话" />
        </el-form-item>
        <!-- <el-form-item label="餐厅信息" prop="restaurantInfo">
          <el-input type="textarea" v-model="form.restaurantInfo" aria-modal="2048" placeholder="请输入餐厅信息" />
        </el-form-item> -->
        <el-upload
          class="avatar-uploader"
          :action="MixinUploadAllApi"
          name="file"
          :show-file-list="false"
          :on-success="uploadSuccess">
        </el-upload>
         <el-form-item label="餐厅信息" prop="restaurantName">
        <quill-editor ref="quillEditor" v-model="restaurantInfo" class="myQuillEditor" :options="editorOption"/>
           </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, exportInfo } from "@/api/restaurant/info";
import { quillEditor } from 'vue-quill-editor';
import { getCompanys } from '@/api/system/dept';
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

const toolbarOptions = [
    ['bold', 'italic', 'underline'],        // toggled buttons
    ['blockquote', 'code-block'],
    [{'header': 1}],               // custom button values
    [{'list': 'ordered'}],
    [{'direction': 'rtl'}],                         // text direction

    [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],

    [{'color': []}, {'background': []}],          // dropdown with defaults from theme
    [{'font': []}],
    [{'align': []}],
    ['link', 'image', 'video'],
    ['clean']                                         // remove formatting button
]
export default {
  components: {
    quillEditor
  },
  name: "Info",
  data() {
    return {
        MixinUploadAllApi: process.env.VUE_APP_BASE_API + "/file/upload/single",
      // 遮罩层
      loading: true,

      restaurantInfo: '',
      editorOption: {},

      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        restaurantName: undefined,
        restaurantInfo: undefined,
      },
      // 表单参数
      form: {},
      // 公司信息
      companys: [],
      // 表单校验
      rules: {
        restaurantName: [
          { required: true, message: "餐厅名称不能为空", trigger: "blur" }
        ],
        restaurantInfo: [
          { required: true, message: "餐厅信息不能为空", trigger: "blur" }
        ],
        telephone: [
          { required: true, message: "餐厅联系电话不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        companyId: [
            { required: true, message: '请选择所属公司', trigger: 'change' }
        ],
      },
      editorOption: {
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
              toolbar: {
                  container: toolbarOptions,  // 工具栏
                  handlers: {
                      'image': function (value) {
                          if (value) {
                              //****就是这里自定义了图片上传的事件****
                              //你们可以alert(1111)试下有没有成功
                              document.querySelector('.avatar-uploader input').click()
                          } else {
                              this.quill.format('image', false);
                          }
                      }
                  }
              }
          }
      },
    };
  },
  created() {
    this.getList();
    this.getCompanyList();
  },
  methods: {
      uploadSuccess(res, file) {
          console.log('图片上传到服务器',file.response.data)
          //res为图片服务器返回的数据
          //获取富文本组件实例
          let quill = this.$refs.quillEditor.quill
          console.log('uploadSuccess的res',res)
          // 如果上传成功
          if (res.code == 0 && res.data !== null) {
              // 获取光标所在位置
              let length = quill.getSelection().index;
              // 插入图片  res.info为服务器返回的图片地址
              quill.insertEmbed(length, 'image', res.data)
              // 调整光标到最后
              quill.setSelection(length + 1)
          } else {
              this.$message.error('uploadSuccess图片插入失败')
          }
      },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        restaurantName: undefined,
        restaurantInfo: undefined,
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
      this.restaurantInfo = '';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.restaurantInfo = response.data.restaurantInfo;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {

        console.log("this.restaurantInfo===========" + this.restaurantInfo);
        // let reg=new RegExp('\\','g')//g代表全部
        // let newMsg=JSON.stringify(this.restaurantInfo);
        let newMsg = this.restaurantInfo.replace(/[\\]/g,'')
        console.log("newMsg===========" + newMsg);


        this.form.restaurantInfo = newMsg;
        if (valid) {
          if (this.form.id != undefined) {
            updateInfo(this.form).then(response => {
              if (response.code == '0') {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addInfo(this.form).then(response => {
              if (response.code == '0') {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInfo(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportInfo(queryParams);
        }).then(response => {
          this.download(response.data);
        }).catch(function() {});
    },
    /** 获取公司信息 */
    getCompanyList() {
      getCompanys().then(response => {
        this.companys = response.data;
      });
    },
  }
};
</script>
